﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;

namespace 接收端
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void BtnClear_Click(object sender, EventArgs e)
        {
            textBox1.Clear();
        }

        private void serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            textBox1.AppendText(serialPort.ReadExisting());
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 将所有的端口加载到下拉选项中
            foreach (string portname in SerialPort.GetPortNames())
            {
                comboBox1.Items.Add(portname);
            }
            // 默认选中第一个端口
            if (comboBox1.Items.Count > 0)
            {
                comboBox1.SelectedItem = comboBox1.Items[0];
            }

        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox1.SelectedItem == null)
            {
                return;
            }
            if (serialPort.IsOpen)
            {
                serialPort.Close();
            }
            serialPort.PortName = (string)comboBox1.SelectedItem;
            // 波特率115200
            serialPort.BaudRate = 115200;
            // 数据位8
            serialPort.DataBits = 8;
            // 停止位1
            serialPort.StopBits = StopBits.One;
            // 无校验
            serialPort.Parity = Parity.None;
            serialPort.Encoding = Encoding.UTF8;
            try
            {
                serialPort.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
